<template>
  <div class="menu-page">
    <div id="org-manage">
      <div class="org-manage-page">
        <div class="org-manage-left-tree">
          <el-tree
              :data="orgTree"
              node-key="empty.id"
              @node-click="nodeClick"
          >
            <template #default="{node,data}">
              {{ data.empty.name }}
            </template>
          </el-tree>
        </div>
        <div class="org-manage-right-table">
          <div style="display: flex;flex-direction: row-reverse">
            <el-button-group size="small" style="margin-top: 10px;margin-right: 5px;">
              <el-button link type="danger" icon="Delete"/>
              <el-button link type="primary" icon="Plus" @click="openAdd"/>
            </el-button-group>
          </div>
          <el-table
              :data="orgTable"
          >
            <el-table-column label="组织" prop="name"/>
            <el-table-column label="创建时间">
              <template #default="scope">
                {{ dateFormat(scope.row.createTime) }}
              </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作">
              <template #default="scope">
                <el-button link icon="Edit" type="warning" size="small" @click="editOpt(scope.row,scope.$index)"/>
                <el-popconfirm title="确认删除?"
                               @confirm="deleteOpt(scope.row,scope.$index)"
                >
                  <template #reference>
                    <el-button link icon="Delete" type="danger" size="small"/>
                  </template>
                </el-popconfirm>
              </template>
            </el-table-column>
          </el-table>
          <Pages ref="orgManagePage" @action="paging" @change="changeSize"/>
        </div>
      </div>
    </div>
    <el-dialog
        v-model="addflag"
        width="20%"
        title="创建组织"
        draggable
        @close="closeAdd"
    >
      <el-form
        ref="addFormRef"
        :model="form"
        label-position="left"
        :rules="rules"
      >
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="primary" @click="create(addFormRef)">创建</el-button>
        <el-button @click="addflag=!addflag">取消</el-button>
      </template>
    </el-dialog>
    <el-dialog
        v-model="editflag"
        width="20%"
        title="编辑"
        draggable
    >
      <el-form :model="editForm">
        <el-form-item label="名称">
          <el-input v-model="editForm.name"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="primary" @click="executeEdit">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">

import {userStore} from "../../../../store/user";
import {onMounted, onUnmounted, reactive, ref} from "vue";
import Axios from "../../../../plugins/axios";
import event from "../../../../plugins/event";
import {UpdateOrgAndRoleEvent} from "../../../../plugins/evenKey";
import Pages from "../../../../management-system/components/Pages.vue";
import {dateFormat} from "../../../../utils/utils";
import {sys} from "../../../../model/system";
import {ElMessage, FormInstance, FormRules} from "element-plus";

const user = userStore()
const orgTree = ref([])
const orgTable = ref([])
const selectOrg = ref()
const orgManagePage = ref()
const addflag = ref(false)
const editflag=ref(false)

const addFormRef=ref<FormInstance>()
const form = ref({
  pid: 0,
  name: ''
})

function checkNull(rule: any, value: any, callback: any) {
  if (value===''){
    callback(new Error('必填项!'))
    return
  }
  callback()
}

const rules=reactive<FormRules>({
  // name:[{validator:checkNull,trigger:'blur'}],
})

function closeAdd() {
  addFormRef.value?.resetFields()
}

function openAdd() {
  if (selectOrg.value<1){
    ElMessage({
      type:'warning',
      message:'请选择组织进行添加'
    })
    return
  }
  form.value = {
    pid: selectOrg.value,
    name: ''
  }
  addflag.value = !addflag.value
}

function create(formEl:FormInstance|undefined) {
  if (!formEl) return
  formEl.validate((flag)=>{
    if (flag){
      Axios.post('/api/configuration/org/create', form.value).then(response => {
        let data: sys.Result<any> = response.data
        if (data.code === '0000') {
          ElMessage({
            type: 'success',
            message: data.msg
          })

          // 重新加载树
          Axios.get('/api/configuration/org/list', {
            params: {
              org: user.userInfo.org
            }
          }).then(response => {
            let data = response.data
            if (data.code === "0000") {
              orgTree.value = data.data
            }
          })

          // 加载子数据
          let page = orgManagePage.value.GetPageNum()
          let size = orgManagePage.value.GetSize()
          Axios.get('/api/configuration/org/list/child', {
            params: {
              page: page,
              size: size,
              pid: selectOrg.value
            }
          }).then(function (response) {
            let data = response.data
            if (data.code === "0000") {
              orgTable.value = data.data.rows
              orgManagePage.value.SetTotal(data.data.count)
            }
          })
        }
      })
      addflag.value = !addflag.value
    }else {
      ElMessage({
        type:'warning',
        message:'请填写信息'
      })
    }
  })

}


const editForm=ref({
  id: 0,
  name: ''
})

function editOpt(row, index) {
  console.log(row)
  editForm.value.id=row.id
  editForm.value.name=row.name
  editflag.value=!editflag.value
}

function executeEdit() {
  editflag.value=!editflag.value
}


function deleteOpt(row, index) {
  Axios.post('/api/configuration/org/del',{
    id:row.id
  }).then(response=>{
    let data:sys.Result<any> =response.data
    if (data.code==='0000'){
      ElMessage({
        type: 'success',
        message: data.msg
      })
      // 加载数据
      // 重新加载树
      Axios.get('/api/configuration/org/list', {
        params: {
          org: user.userInfo.org
        }
      }).then(response => {
        let data = response.data
        if (data.code === "0000") {
          orgTree.value = data.data
        }
      })

      // 加载子数据
      let page = orgManagePage.value.GetPageNum()
      let size = orgManagePage.value.GetSize()
      Axios.get('/api/configuration/org/list/child', {
        params: {
          page: page,
          size: size,
          pid: selectOrg.value
        }
      }).then(function (response) {
        let data = response.data
        if (data.code === "0000") {
          orgTable.value = data.data.rows
          orgManagePage.value.SetTotal(data.data.count)
        }
      })
    }
  })
}

function nodeClick(data, node) {
  selectOrg.value = data.empty.id
  let size = orgManagePage.value.GetSize()
  Axios.get('/api/configuration/org/list/child', {
    params: {
      pid: selectOrg.value,
      page: 1,
      size: size
    }
  }).then(response => {
    let data = response.data
    if (data.code === "0000") {
      orgTable.value = data.data.rows
      orgManagePage.value.SetTotal(data.data.count)
    }
  })
}

function paging(newPage, size) {
  // 执行翻页
  Axios.get('/api/configuration/org/list/child', {
    params: {
      page: newPage,
      size: size,
      pid: selectOrg.value
    }
  }).then(function (response) {
    let data = response.data
    if (data.code === "0000") {
      orgTable.value = data.data.rows
      orgManagePage.value.SetTotal(data.data.count)
    }
  })
}

function changeSize(page: number, size: number) {
  Axios.get('/api/configuration/org/list/child', {
    params: {
      page: page,
      size: size,
      pid: selectOrg.value
    }
  }).then(function (response) {
    let data = response.data
    if (data.code === "0000") {
      orgTable.value = data.data.rows
      orgManagePage.value.SetTotal(data.data.count)
    }
  })
}

function init() {
  selectOrg.value = user.userInfo.org
  Axios.get('/api/configuration/org/list', {
    params: {
      org: selectOrg.value
    }
  }).then(response => {
    let data = response.data
    if (data.code === "0000") {
      orgTree.value = data.data
    }
  })
  let size = orgManagePage.value.GetSize();
  Axios.get('/api/configuration/org/list/child', {
    params: {
      pid: selectOrg.value,
      page: 1,
      size: size,
    }
  }).then(response => {
    let data = response.data
    if (data.code === "0000") {
      orgTable.value = data.data.rows
      orgManagePage.value.SetTotal(data.data.count)
    }
  })
}

onMounted(init)
event.on(UpdateOrgAndRoleEvent, init)
onUnmounted(() => {
  event.off(UpdateOrgAndRoleEvent, init)
})

</script>

<style scoped>
#org-manage {
  width: 100%;
  display: flex;
  flex-direction: row;
  justify-content: center;
}

.org-manage-page {
  width: 97%;
  height: 800px;
  margin: auto;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
}

.org-manage-left-tree, .org-manage-right-table {
  box-shadow: var(--el-box-shadow-light);
  background-color: white;
}

.org-manage-left-tree {
  width: 20%;
}

.org-manage-right-table {
  width: 79%;
}
</style>